<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="formData.id ? '编辑菜品' : '新增菜品'"
    width="700px"
  >
    <el-form :model="formData" label-width="120px" ref="formRef" :rules="rules">
      <!-- 商家选择 -->
      <el-form-item label="选择商家" prop="sellerId">
        <el-select v-model="formData.sellerId" placeholder="请选择商家" filterable @change="handleSellerChange">
          <el-option
            v-for="item in sellerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <!-- 菜品分类 -->
      <el-form-item label="菜品分类" prop="category">
        <el-select v-model="formData.category" placeholder="请选择菜品分类">
          <el-option label="热菜" value="热菜" />
          <el-option label="凉菜" value="凉菜" />
          <el-option label="主食" value="主食" />
          <el-option label="汤品" value="汤品" />
          <el-option label="甜点" value="甜点" />
          <el-option label="饮品" value="饮品" />
        </el-select>
      </el-form-item>
      
      <!-- 菜品名称 -->
      <el-form-item label="菜品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入菜品名称" />
      </el-form-item>
      
      <!-- 菜品价格 -->
      <el-form-item label="菜品价格" prop="price">
        <el-input-number v-model="formData.price" :precision="2" :min="0" placeholder="请设置菜品价格" />
      </el-form-item>
      
      <!-- 菜品主图 -->
      <el-form-item label="菜品主图" prop="image">
        <UploadFile
          v-model="formData.image"
          action="/api/upload"
          :limit="1"
          :file-size="5"
          @success="handleUploadSuccess"
        />
        <div class="tips">建议尺寸: 800 x 800px，支持jpg、png格式，最大5MB</div>
      </el-form-item>
      
      <!-- 菜品详情描述 -->
      <el-form-item label="详情描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请输入菜品详情描述"
        />
      </el-form-item>
      
      <!-- 购买须知 -->
      <el-form-item label="购买须知" prop="purchaseNotes">
        <el-input
          v-model="formData.purchaseNotes"
          type="textarea"
          :rows="4"
          placeholder="请输入购买须知"
        />
        <div class="tips">例如：食用方法、保质期、配送时间等信息</div>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import Dialog from "@/components/dialog.vue";
import UploadFile from "@/components/UploadFile.vue";
import { ElMessage } from 'element-plus';

const show = defineModel();
const emit = defineEmits(['update', 'success']);

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

// 监听弹窗显示状态，回显数据
watch(show, (val) => {
  if (val) {
    if (props.data && Object.keys(props.data).length > 0) {
      // 编辑模式，回显数据
      formData.value = {
        ...props.data,
        // 确保图片字段的格式统一
        image: props.data.image ? [props.data.image] : [],
      };
    } else {
      // 新增模式，重置表单
      resetForm();
    }
  }
});

// 表单数据
const formData = ref({
  id: '',
  sellerId: '',
  sellerName: '',
  category: '',
  name: '',
  price: 0,
  image: [],
  description: '',
  purchaseNotes: '',
});

// 表单验证规则
const rules = ref({
  sellerId: [{ required: true, message: "请选择商家", trigger: "change" }],
  category: [{ required: true, message: "请选择菜品分类", trigger: "change" }],
  name: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
  price: [{ required: true, message: "请设置菜品价格", trigger: "blur" }],
  image: [{ required: true, message: "请上传菜品主图", trigger: "blur" }],
  description: [{ required: true, message: "请输入菜品详情描述", trigger: "blur" }],
  purchaseNotes: [{ required: true, message: "请输入购买须知", trigger: "blur" }],
});

const formRef = ref();

// 商家选项列表（模拟数据，实际项目中应该从API获取）
const sellerOptions = ref([
  { id: 'SELLER0001', name: '商家1', address: '北京市朝阳区建国路88号', contactPerson: '联系人1', contactPhone: '13912340000' },
  { id: 'SELLER0002', name: '商家2', address: '北京市海淀区中关村大街1号', contactPerson: '联系人2', contactPhone: '13912341111' },
  { id: 'SELLER0003', name: '商家3', address: '北京市西城区西单大街10号', contactPerson: '联系人3', contactPhone: '13912342222' },
  { id: 'SELLER0004', name: '商家4', address: '北京市东城区东直门内大街8号', contactPerson: '联系人4', contactPhone: '13912343333' },
  { id: 'SELLER0005', name: '商家5', address: '北京市丰台区丰台路20号', contactPerson: '联系人5', contactPhone: '13912344444' },
]);

// 获取商家列表
onMounted(() => {
  // 实际项目中，这里应该调用API获取商家列表
  // fetchSellerList();
});

// 处理商家选择变化
const handleSellerChange = (sellerId) => {
  const seller = sellerOptions.value.find(item => item.id === sellerId);
  if (seller) {
    formData.value.sellerName = seller.name;
    formData.value.address = seller.address;
    formData.value.contactPerson = seller.contactPerson;
    formData.value.contactPhone = seller.contactPhone;
  }
};

// 处理图片上传成功
const handleUploadSuccess = (res, file) => {
  // 实际项目中，这里应该处理上传接口的返回结果
  // formData.value.image = [res.url];
  ElMessage.success('图片上传成功');
};

// 重置表单
const resetForm = () => {
  formData.value = {
    id: '',
    sellerId: '',
    sellerName: '',
    category: '',
    name: '',
    price: 0,
    image: [],
    description: '',
    purchaseNotes: '',
  };
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 处理图片数据格式
      const submitData = {
        ...formData.value,
        image: formData.value.image[0], // 取第一张图片作为主图
        publishTime: formData.value.id ? formData.value.publishTime : new Date().toISOString().split('T')[0], // 新增时设置发布时间
        status: '1', // 默认状态为在售
        serialNumber: formData.value.id ? formData.value.serialNumber : `DISH${Date.now().toString().slice(-8)}`, // 新增时生成序号
      };
      
      // 提交数据
      emit('success', submitData);
      ElMessage.success(`${formData.value.id ? '编辑' : '新增'}菜品成功`);
      
      // 关闭弹窗
      close();
    } else {
      return false;
    }
  });
};

// 关闭弹窗
const close = () => {
  show.value = false;
  resetForm();
};
</script>

<style scoped>
.tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
